import pygame
import random

import Sprite_Group
import Bullets
import  StatusBars
from Config import ENEMYLV
from My_functions import  auto_move
from Skins import Enemy_skins

class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y,level):
        super().__init__()
        # 移动图像
        self.level =level
        self.images =Enemy_skins[level-1]
        self.bulletskin = Enemy_skins[level-1]['Bullet']
        # 初始化方向
        self.direction = self.randomd()
        # 初始化图像
        self.current_frame = 0
        self.frame_rate = 6
        self.current_rate = 0
        self.image = self.images[self.direction][self.current_frame]
        # 获取图像参数
        self.rect = self.image.get_rect()
        # 为图像参数赋值
        self.rect.x = x
        self.rect.y = y
        # 初始速度
        self.move_speed =ENEMYLV[level][2]
        # 射速
        self.shot_speed =ENEMYLV[level][3]
        # 控制射速
        self.last_time = 0
        # 是否存活
        self.live = True

        #随机移动
        self.step=0
        self.steplim=ENEMYLV[level][1]
        #生命值
        #最大生命值
        self.max_hp=ENEMYLV[level][0]
        self.hp =self.max_hp

        healthbar = StatusBars.StatusBar(self)
        Sprite_Group.StatusBar_grop.add(healthbar)

    def shot(self):
        now_time = pygame.time.get_ticks()
        if now_time - self.last_time >= self.shot_speed:
            self.last_time = now_time
            b = Bullets.EnemyBullet(self)
            Sprite_Group.Enemy_Bullet_group.add(b)

    def is_live(self):
        if self.hp<=0:self.live=False

    @staticmethod
    def randomd():
        return random.choice(['U', 'D', 'L', 'R'])

    def randommove(self):
        self.old_pos = (self.rect.x, self.rect.y)
        if self.step>=self.steplim:
            self.step=0
            return self.randomd()
        self.step+=random.randint(1,5)
        return self.direction

    def update(self, *args, **kwargs):
        self.is_live()
        auto_move(self,self.move_speed,self.randommove())
        if len(Sprite_Group.Enemy_Bullet_group)<10:self.shot()
        self.current_rate += 1
        if self.current_rate > self.frame_rate:
            self.current_frame = (self.current_frame + 1) % len(self.images[self.direction])
            self.current_rate = 0